package com.ywl.study.transaction.netty;

import com.alibaba.fastjson.JSONObject;
import com.ywl.study.transaction.transaction.DistirctTransactionManager;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class NettyClient {

    NettyClientHandler clientHandler;
    ChannelFuture channelFuture;

    @PostConstruct
    public void start(){
        log.info("自动连接分布式事务管理器。。。。");
        connect("localhost",8080);
    }
    public void connect(String host,int port){
        EventLoopGroup worker=new NioEventLoopGroup();
        try{
            //客户端启动类程序
            Bootstrap bootstrap=new Bootstrap();
            //EventLoop的组
            bootstrap.group(worker);
            //用于构造socketchannel工厂
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new NettyClientHandler());
                }
            });
            //开启客户端监听，连接到远程节点，阻塞等待直到连接完成
             channelFuture=bootstrap.connect(host,port).sync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public synchronized Object send(JSONObject data){
        channelFuture.channel().writeAndFlush(data.toJSONString());
        log.info("netty client 发送数据:"+data.toJSONString());
        return null;
    }

    public void close() throws InterruptedException {
        //阻塞等待数据，直到channel关闭
        channelFuture.channel().closeFuture().sync();
    }

}
